import { constantRoutes, asyncRoutes } from '@/router'
import { LAYOUT } from '../../router/permission'
// -------筛选路由
const hasPermission = (permissions, route) => {
  if (route.meta && route.meta.permission) {
    return permissions.includes(route.meta.permission)
  } else {
    return true
  }
}
export const filterAsyncRoutes = (routes, permissions) => {
  const res = []
  routes.forEach(route => {
    const r = { ...route }
    if (hasPermission(permissions, r)) {
      if (r.children) {
        r.children = filterAsyncRoutes(r.children, permissions)
      }
      if (r.component === LAYOUT) {
        r.children.length > 0 ? res.push(r) : res.push()
      } else {
        res.push(r)
      }
    }
  })
  return res
}
// 递归取出所有路由name
const getRouteName = (routes) => {
  const nameList = []
  const setList = (arr) => {
    arr.forEach(item => {
      nameList.push(item.name)
      if (item.children && item.children.length > 0) {
        setList(item.children)
      }
    })
  }
  setList(routes)
  return nameList
}

const Permission = {
  namespaced: false,
  state: {
    routes: [],
    dynamicRoutes: [],
    routeNames: [],
    permissions: []
  },
  getters: {
    routeNames: state => state.routeNames,
    routes: state => state.routes,
    dynamicRoutes: state => state.dynamicRoutes,
    permissions: state => state.permissions
  },
  mutations: {
    SET_PERMISSION (state, value) {
      state.permissions = value
    },
    SET_RouteNames (state, value) {
      state.routeNames = value
    },
    SET_ROUTES (state, routes) {
      state.routes = constantRoutes.concat(routes)
      state.dynamicRoutes = routes
    }
  },
  actions: {
    async initPermission ({ commit, state }, params) {
      commit('SET_RouteNames', getRouteName(state.routes))
    },
    GenerateRoutes ({ commit, dispatch, state }, roles) {
      let accessedRoutes = []
      // TODO: 根据权限 构建路由
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, state.permissions)
      }
      commit('SET_ROUTES', accessedRoutes)
      dispatch('initPermission')
    }
  }
}

export default Permission
